package com.mantru.iotpot.setting;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.mantru.iotpot.Begin.LoginActivity;
import com.mantru.iotpot.R;
import com.mantru.iotpot.setting.Adapter.MyWiFiAdapter;
import com.mantru.iotpot.setting.Adapter.OtherWiFiAdapter;

import java.util.ArrayList;
import java.util.List;

public class WiFiActivity extends AppCompatActivity implements OtherWiFiAdapter.OnWiFiConnectListener {

    private LinearLayout back;
    private RecyclerView my_wifi;
    private RecyclerView other_wifi;
    private WifiManager wifiManager;
    private MyWiFiAdapter myWiFiAdapter;
    private OtherWiFiAdapter otherWiFiAdapter;
    private List<String> connectedWifiList = new ArrayList<>();
    private List<String> nearbyWifiList = new ArrayList<>();
    private int star;

    private final BroadcastReceiver wifiScanReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
                if (ActivityCompat.checkSelfPermission(WiFiActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    return;
                }
                List<ScanResult> scanResults = wifiManager.getScanResults();
                nearbyWifiList.clear();
                for (ScanResult result : scanResults) {
                    String ssid = result.SSID.replace("\"", "");
                    if (!ssid.isEmpty() && !connectedWifiList.contains(ssid)) {
                        nearbyWifiList.add(ssid);
                    }
                }
                otherWiFiAdapter.notifyDataSetChanged();
            }
        }
    };

    private final BroadcastReceiver wifiStateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(action)) {
                NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
                if (networkInfo.getState() == NetworkInfo.State.CONNECTED) {
                    Toast.makeText(context, "WiFi 连接成功", Toast.LENGTH_SHORT).show();
                    getConnectedWifi();
                    setupRecyclerViews();
                    closeWaitDialog();
                } else if (networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
                    Toast.makeText(context, "WiFi 连接失败", Toast.LENGTH_SHORT).show();
                    closeWaitDialog();
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wi_fi);
        star = getIntent().getIntExtra("net", 0);
        Log.d("WiFiActivity", "star: " + star);
        initialization();
    }

    private void initialization() {
        back = findViewById(R.id.wifi_back);
        my_wifi = findViewById(R.id.my_wifi_recyclerview);
        other_wifi = findViewById(R.id.other_wifi_recyclerview);

        back.setOnClickListener(v -> {
            if (star == 0) {
                finish();
            } else if (star == 1) {
                startActivity(new Intent(this, LoginActivity.class));
                finish();
            }
        });

        wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED ||
                ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_WIFI_STATE)
                        != PackageManager.PERMISSION_GRANTED ||
                ContextCompat.checkSelfPermission(this, Manifest.permission.CHANGE_WIFI_STATE)
                        != PackageManager.PERMISSION_GRANTED) {
            requestLocationPermission();
        } else {
            getConnectedWifi();
            scanNearbyWifi();
            setupRecyclerViews();
        }
        registerReceiver(wifiScanReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
        registerReceiver(wifiStateReceiver, new IntentFilter(WifiManager.NETWORK_STATE_CHANGED_ACTION));
    }

    private void requestLocationPermission() {
        ActivityResultLauncher<String[]> permissionLauncher = registerForActivityResult(
                new ActivityResultContracts.RequestMultiplePermissions(),
                permissions -> {
                    boolean granted = true;
                    for (boolean value : permissions.values()) {
                        if (!value) {
                            granted = false;
                            break;
                        }
                    }
                    if (granted) {
                        getConnectedWifi();
                        scanNearbyWifi();
                        setupRecyclerViews();
                    } else {
                        Toast.makeText(this, "权限未授予", Toast.LENGTH_SHORT).show();
                    }
                });
        permissionLauncher.launch(new String[]{
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_WIFI_STATE,
                Manifest.permission.CHANGE_WIFI_STATE
        });
    }

    private void getConnectedWifi() {
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        String connectedSsid = wifiInfo.getSSID();
        if (connectedSsid != null && !connectedSsid.isEmpty()) {
            connectedSsid = connectedSsid.replace("\"", "");
            connectedWifiList.clear();
            connectedWifiList.add(connectedSsid);
        }
    }

    private void scanNearbyWifi() {
        if (wifiManager.startScan()) {
            Log.d("WiFiActivity", "Scan started successfully");
        } else {
            Log.e("WiFiActivity", "Failed to start scan");
        }
    }

    private void setupRecyclerViews() {
        my_wifi.setLayoutManager(new LinearLayoutManager(this));
        myWiFiAdapter = new MyWiFiAdapter(connectedWifiList);
        my_wifi.setAdapter(myWiFiAdapter);

        other_wifi.setLayoutManager(new LinearLayoutManager(this));
        otherWiFiAdapter = new OtherWiFiAdapter(this, nearbyWifiList, this);
        other_wifi.setAdapter(otherWiFiAdapter);
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(wifiScanReceiver);
        unregisterReceiver(wifiStateReceiver);
        super.onDestroy();
    }

    @Override
    public void onWiFiConnectStateChanged() {
        closeWaitDialog();
    }

    private void closeWaitDialog() {
        if (otherWiFiAdapter != null && otherWiFiAdapter.waitDialog != null && otherWiFiAdapter.waitDialog.isShowing()) {
            otherWiFiAdapter.waitDialog.dismiss();
        }
    }
}